//
//  HomeRefreshControl.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/21.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit

class HomeRefreshControl: UIRefreshControl {

    var refreshView: HomeRefreshView?
    // 加载xib
    private func loadrefreshview() {
        let r = NSBundle.mainBundle().loadNibNamed("HomeRefresh", owner: nil, options: nil).last as! HomeRefreshView
        self.addSubview(r)
        
        // 设置约束
        r.setTranslatesAutoresizingMaskIntoConstraints(false)
        var cons = [AnyObject]()
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[r(136)]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["r": r])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[r(60)]", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: ["r": r])
        cons.append(NSLayoutConstraint(item: r, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        self.addConstraints(cons)
        refreshView = r
        
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    
    // 监控下拉刷新,实现图标变换
    var isloading = false
    var rotateTip = false
    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
        
        if self.frame.origin.y > 0 {
            return
        }
        
        // 刷新动画
        if (self.refreshing && !isloading) {
            refreshView?.startLoading()
            isloading = true
            return
        }
        
        // 箭头动画,向下
        if self.frame.origin.y < -60 && !rotateTip{
            rotateTip = true
            refreshView?.rotateTipIcon(rotateTip)
        }
        // 降头向上
        else if self.frame.origin.y > -60  && rotateTip{
            rotateTip = false
            refreshView?.rotateTipIcon(rotateTip)
        }
    }
    
    
    override func endRefreshing() {
        // 结束刷新
        super.endRefreshing()
        
        // 停止动画
        refreshView?.stopLoading()
        
        // 重新设置刷新标记
        isloading = false
    }
    
    
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    
    override init() {
        super.init()
        loadrefreshview()
    }
    
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        loadrefreshview()
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        loadrefreshview()
    }
}




class HomeRefreshView: UIView {
    
    @IBOutlet weak var loadinImg: UIImageView!
    
    // 指示箭头
    @IBOutlet weak var arrowImg: UIImageView!
    
    // tip提示
    @IBOutlet weak var msgLbl: UILabel!
    
    // tip的view
    @IBOutlet weak var coverView: UIView!
    
    
    // 刷新动画
    var isloading = false
    func startLoading() {
        if isloading {
            return
        }
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.toValue = M_PI * 2
        loadinImg.layer.addAnimation(anim, forKey: nil)
        coverView.hidden = true
        isloading = true
    }
    
    
    func stopLoading() {
        loadinImg.layer.removeAllAnimations()
        coverView.hidden = false
        isloading = false
    }
    
    
    // 箭头转换
    func rotateTipIcon(clockWise: Bool) {
        var angel:CGFloat = CGFloat(M_PI)
        angel += clockWise ? -0.01 : 0.01
        UIView.animateWithDuration(0.5) {
            self.arrowImg.transform = CGAffineTransformRotate(self.arrowImg.transform, angel)
        }
    }

}








